package guda.house.biz.security;

import guda.grape.mvc.security.auth.AuthPattern;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;

/**
 * Created by well on 15/11/21.
 */
public class SecurityUtil {

    private static Map<String,AuthPattern> resourceCache = new ConcurrentHashMap<String, AuthPattern>(500) {
    };

    public static boolean access(Object obj){
        if(obj == null){
            return false;
        }
        String url = String.valueOf(obj);
        if(!url.startsWith("/")){
            url = "/"+url;
        }
        if(AuthUser.getCurrentUser() == null){
            return false;
        }
        List<String> resourceList = AuthUser.getCurrentUser().getResourceList();
        if(resourceList == null){
            return false;
        }
        for(String resource:resourceList){
            AuthPattern pattern = resourceCache.get(resource);
            if(pattern == null){
                pattern = new AuthPattern(resource);
                resourceCache.put(resource,pattern);
            }
            Matcher matcher = pattern.matcher(url);
            if(matcher.find()){
                return true;
            }
        }
        return false;
    }

    public static boolean accessSubMenu(Object obj){
        if(obj == null){
            return false;
        }
        String url = String.valueOf(obj);
        if(!url.startsWith("/")){
            url = "/"+url;
        }
        if(AuthUser.getCurrentUser() == null){
            return false;
        }
        List<String> resourceList = AuthUser.getCurrentUser().getResourceList();
        if(resourceList == null){
            return false;
        }
        for(String resource:resourceList){
            if(resource.startsWith(url)){
                return true;
            }
        }
        return false;
    }
}
